package jzbank.dao.serializabledao.impl;

import jzbank.common.exception.SyncException;
import jzbank.dao.serializabledao.TaskDao;
import jzbank.pojo.vo.TaskInfo;
import jzbank.util.SerializationUtil;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class TaskDaoImpl implements TaskDao {

    private static final String DATA_FILE = "./task/taskinfo_data.ser";

    // 增加任务信息
    @Override
    public void addTaskInfo(TaskInfo taskInfo) {
        List<TaskInfo> taskInfoList = getAllTaskInfo();
        taskInfoList.add(taskInfo);
        System.out.println("dao！");

        SerializationUtil.serializeObjectToFile(taskInfoList, DATA_FILE);

    }

    // 删除任务信息
    @Override
    public void deleteTaskInfo(String id) {
        List<TaskInfo> taskInfoList = getAllTaskInfo();
        taskInfoList.removeIf(taskInfo -> taskInfo.getTid() == id);

        SerializationUtil.serializeObjectToFile(taskInfoList, DATA_FILE);

    }

    // 更新任务信息
    @Override
    public void updateTaskInfo(TaskInfo updatedTaskInfo) {
        List<TaskInfo> taskInfoList = getAllTaskInfo();
        for (int i = 0; i < taskInfoList.size(); i++) {
            if (taskInfoList.get(i).getTid().equals(updatedTaskInfo.getTid())) {
                taskInfoList.set(i, updatedTaskInfo);
                break;
            }
        }

        SerializationUtil.serializeObjectToFile(taskInfoList, DATA_FILE);

    }

    // 获取所有任务信息
    @Override
    public List<TaskInfo> getAllTaskInfo() {
        List<TaskInfo> taskInfoList = new ArrayList<>();

        Object obj = SerializationUtil.deserializeObjectFromFile(DATA_FILE);
        if (obj instanceof List<?>) {
            taskInfoList = (List<TaskInfo>) obj;
        }

        return taskInfoList;
    }

    //根据任务id查找任务信息
    @Override
    public TaskInfo getTaskInfoByTid(String tid) {
        List<TaskInfo> taskInfoList = getAllTaskInfo();
        TaskInfo taskInfo = new TaskInfo();
        for (int i = 0; i < taskInfoList.size(); i++) {
            if (taskInfoList.get(i).getTid().equals(tid)) {
                taskInfo = taskInfoList.get(i);
                break;
            }
        }
        return taskInfo;
    }

    @Override
    public TaskInfo getTaskInfoByName(String name) {
        System.out.println("查找：" + name);
        List<TaskInfo> taskInfoList = getAllTaskInfo();
        TaskInfo taskInfo = new TaskInfo();
        for (int i = 0; i < taskInfoList.size(); i++) {
            if (taskInfoList.get(i).getTaskCode().equals(name)) {
                taskInfo = taskInfoList.get(i);
                break;
            }
        }
        System.out.println("返回" + name);
        return taskInfo;
    }

}
